let lifeData = uni.getStorageSync('lifeData') || {};

let $cart = lifeData.$cart || {};

export default {
  namespaced: true, // 使用命名空间

  state: {
    cartItems: $cart.cartItems || [
          {
            id: 1,
            name: '[哈勃号直供] 哈勃车业保养 金美孚机油',
            spec: '4升',
            price: 99,
            num: 1,
            checked: true,
            image: 'https://env-00jxt1fzew48.normal.cloudstatic.cn/car/car.png'
          },
          {
            id: 2,
            name: '[哈勃号直供] 哈勃车业保养 金美孚机油',
            spec: '4升',
            price: 99,
            num: 1,
            checked: false,
            image: 'https://env-00jxt1fzew48.normal.cloudstatic.cn/car/car.png'
          }
        ],
        isEditing: $cart.isEditing || false,
  },

 getters: {
     selectedItems: (state) => state.cartItems.filter((item) => item.checked),
     totalPrice: (state) =>
       state.cartItems
         .filter((item) => item.checked)
         .reduce((total, item) => total + item.price * item.num, 0)
         .toFixed(2),
     isAllSelected: (state) => state.cartItems.every((item) => item.checked),
     selectedCount: (state) =>
       state.cartItems
         .filter((item) => item.checked)
         .reduce((total, item) => total + item.num, 0),
   },
 
   mutations: {
     ADD_ITEM(state, item) {
       state.cartItems.push(item);
     },
     REMOVE_ITEM(state, id) {
       state.cartItems = state.cartItems.filter((item) => item.id !== id);
     },
     UPDATE_ITEM_QUANTITY(state, { index, quantity }) {
       if (state.cartItems[index]) {
         state.cartItems[index].num = parseInt(quantity, 10);
       }
     },
     TOGGLE_EDIT(state) {
       state.isEditing = !state.isEditing;
     },
     TOGGLE_ITEM_CHECKED(state, index) {
       if (state.cartItems[index]) {
         state.cartItems[index].checked = !state.cartItems[index].checked;
       }
     },
     SET_ALL_CHECKED(state, isChecked) {
       state.cartItems.forEach((item) => {
         item.checked = isChecked;
       });
     },
   },
 
   actions: {
     addItem({ commit }, item) {
       commit('ADD_ITEM', item);
     },
     removeItem({ commit }, id) {
       commit('REMOVE_ITEM', id);
     },
     updateItemQuantity({ commit }, payload) {
       commit('UPDATE_ITEM_QUANTITY', payload);
     },
     toggleEdit({ commit }) {
       commit('TOGGLE_EDIT');
     },
     toggleItemChecked({ commit }, index) {
       commit('TOGGLE_ITEM_CHECKED', index);
     },
     setAllChecked({ commit }, isChecked) {
       commit('SET_ALL_CHECKED', isChecked);
     },
     handleSettlement({ getters }) {
       const selectedItems = getters.selectedItems;
       console.log('结算商品：', selectedItems);
       // 这里可以调用 API 提交订单
     },
   },
};